package com.example.demo.controller.rmw;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;


@Slf4j
public class S3RenameFileExample {
    public static void main(String[] args) {
        // 替换为你的 AWS 访问密钥和密钥 ID
        String accessKey = "597TPSH9P92HGHDVAMMY";
        String secretKey = "UvsQnXTbC7jKkfcBzlQ1q9Ccry5LUfXJFLM2QszR";
        // 替换为你的 AWS 区域
        String region = "cn-beijing";
        String endpoint = "https://huabei-2.zos.ctyun.cn";
        // 替换为你的 S3 存储桶名称
        String bucketName = "bucket-meizi-logfile";
        // 原对象的键（文件名）
        String oldKey = "upload/vod/user1735982106105323/1745548851521111/origin.mp4";
        // 新对象的键（文件名）
        String newKey = "upload/vod/user1735982106105323/1745548851521111/origin_bak.mp4";

        // 创建 AWS 凭证
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
        // 创建 S3 客户端并配置 endpoint
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region))
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .build();
//        denyAllAccess(s3Client);

// 发送 HeadObject 请求获取元数据
        HeadObjectRequest request = HeadObjectRequest.builder()
                .bucket(bucketName)
                .key("upload/vod/user1735982106105323/1747384101819329/origin.mp4")
                .build();

//        HeadObjectResponse response = s3Client.headObject(request);
//        long fileSizeInBytes = response.contentLength(); // 字节大小
//        s3Client.getObject()
        GetObjectMetadataRequest request1 = new GetObjectMetadataRequest(bucketName, "upload/vod/user1735982106105323/1747384101819329/origin.mp4");
        ObjectMetadata objectMetadata = s3Client.getObjectMetadata(request1);
        long fileSizeInBytes = objectMetadata.getContentLength();
        log.info("文件大小为：{} 字节", fileSizeInBytes);
        // 转换为可读格式
        String humanReadableSize = convertFileSize(fileSizeInBytes);

        System.out.println("文件大小：" + humanReadableSize);
        try {
            // 复制对象到新的键下
//            CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, oldKey, bucketName, newKey);
//            s3Client.copyObject(copyObjRequest);
//
//            // 删除原对象
//            DeleteObjectRequest deleteObjRequest = new DeleteObjectRequest(bucketName, oldKey);
//            s3Client.deleteObject(deleteObjRequest);

            // 恢复访问
//            if (!StringUtils.isEmpty(newKey) && newKey.contains("_bak")) {
//                oldKey = newKey.replace("_bak","");
//                log.info("AwsS3OssService--->retrieveFileKey---oldKey:{}",oldKey);
//                // 复制对象到新的名称
//                CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, newKey, bucketName, oldKey);
//                s3Client.copyObject(copyObjRequest);
//
//                // 删除原对象
//                DeleteObjectRequest deleteObjRequest = new DeleteObjectRequest(bucketName, newKey);
//                s3Client.deleteObject(deleteObjRequest);
//                log.info("AwsS3OssService--->retrieveFileKey---success");
//            }

            // 设置预签名 URL 的有效期（这里设置为 1 小时）
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = expiration.getTime();
            expTimeMillis += 1000 * 60 * 60; // 1 小时
            expiration.setTime(expTimeMillis);

            // 生成预签名 URL 请求
//            GeneratePresignedUrlRequest generatePresignedUrlRequest =
//                    new GeneratePresignedUrlRequest(bucketName, thumbnailKey)
//                            .withMethod(com.amazonaws.HttpMethod.GET)
//                            .withExpiration(expiration);
//
//            // 生成预签名 URL
//            URL preSignedUrl = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
//
//            System.out.println("缩略图的预签名 URL: " + preSignedUrl.toString());

//            System.out.println("文件重命名成功。");
        } catch (AmazonServiceException e) {
            // 处理 AWS 服务异常
            System.err.println("AWS 服务异常: " + e.getErrorMessage());
            e.printStackTrace();
        } catch (SdkClientException e) {
            // 处理 SDK 客户端异常
            System.err.println("SDK 客户端异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static String convertFileSize(long bytes) {
        if (bytes < 1024) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        String pre = "KMGT".charAt(exp-1) + "B";
        return String.format("%.2f %s", bytes / Math.pow(1024, exp), pre);
    }


//    public static void denyAllAccess(AmazonS3 s3Client) {
//        String policyJson = String.format(
//                "{\"Version\":\"2012-10-17\",\"Statement\":[{" +
//                        "\"Effect\":\"Deny\"," +
//                        "\"Principal\":\"*\"," +
//                        "\"Action\":\"s3:*\"," +
//                        "\"Resource\":[\"arn:aws:s3:::%s\",\"arn:aws:s3:::%s/*\"]" +
//                        "}]}", BUCKET_NAME, BUCKET_NAME);
//
//        PutBucketPolicyRequest request = PutBucketPolicyRequest.builder()
//                .bucket(BUCKET_NAME)
//                .policy(policyJson)
//                .build();
//        s3Client.putBucketPolicy(request);
//        System.out.println("已禁止所有访问");
//    }


    /**
     * 恢复名称访问
     */
    public void retrieveFileKey(AmazonS3 s3Client,String bucketName,String newKey) {
        log.info("AwsS3OssService--->retrieveFileKey---newKey:{}",newKey);
        if (!StringUtils.isEmpty(newKey) && newKey.contains("_bak")) {
            String oldKey = newKey.replace("_bak","");
            log.info("AwsS3OssService--->retrieveFileKey---oldKey:{}",oldKey);
            // 复制对象到新的名称
            CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, newKey, bucketName, oldKey);
            s3Client.copyObject(copyObjRequest);

            // 删除原对象
            DeleteObjectRequest deleteObjRequest = new DeleteObjectRequest(bucketName, newKey);
            s3Client.deleteObject(deleteObjRequest);
            log.info("AwsS3OssService--->retrieveFileKey---success");
        }
    }


    public void renameFileKey(AmazonS3 s3Client,String bucketName, String oldKey) {
        String newKey = generateNewKey(oldKey);
        log.info("AwsS3OssService--->renameFileKey---oldKey:{},newKey:{}", oldKey, newKey);
        // 复制对象到新的名称
        CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, oldKey, bucketName, newKey);
        s3Client.copyObject(copyObjRequest);

        // 删除原对象
        DeleteObjectRequest deleteObjRequest = new DeleteObjectRequest(bucketName, oldKey);
        s3Client.deleteObject(deleteObjRequest);
        log.info("AwsS3OssService--->renameFileKey---success");

    }

    /**
     * 通用路径生成方法
     * @param originalKey 原始对象路径
     * @return 新路径（自动添加 _bak 后缀）
     */
    private static String generateNewKey(String originalKey) {
        int lastSlashIndex = originalKey.lastIndexOf('/');
        int lastDotIndex = originalKey.lastIndexOf('.');

        // 处理无扩展名文件（如：file → file_bak）
        if (lastDotIndex == -1 || lastDotIndex < lastSlashIndex) {
            return originalKey + "_bak";
        }

        // 分解文件名和扩展名
        String fileName = originalKey.substring(lastSlashIndex + 1, lastDotIndex);
        String extension = originalKey.substring(lastDotIndex);

        // 构造新文件名
        String newFileName = fileName + "_bak" + extension;

        // 组合完整路径
        return originalKey.substring(0, lastSlashIndex + 1) + newFileName;
    }
}    